package offer.easy.math;

public class Fibonacci {

    //斐波那契数列，可采用方法，迭代计算or递归计算

    public static int fibonacci(int n) {
        int[] array = new int[n+1];
        array[0] = 0;
        array[1] = 1;
        array[2] = 1;
        for (int i = 3;i <= n;i++) {
            array[i] = array[i-1] + array[i-2];
        }
        return array[n];
    }

    public static int fibonacci2(int n) {
        if (n == 0) {
            return 0;
        } else if (n == 2 || n == 1) {
            return 1;
        } else {
            return (fibonacci2(n-1) + fibonacci2(n-2));
        }
    }

    public static int fibonacci3(int n) {
        if (n == 0) {
            return 0;
        }

        int a = 0;
        int b = 1;
        int sum = 0;

        for (int i = 2; i <= n; i++) {
            sum = a + b;
            a = b;
            b = sum;
        }

        return sum;
    }

    public static void main(String[] args) {
        System.out.println(fibonacci(39));
        System.out.println(fibonacci2(39));
        System.out.println(fibonacci3(39));
    }
}
